import appApi from '@/sheep/api/app';
import { defineStore } from 'pinia';
import $router from '@/sheep/router';
import { appVersion, debug } from '@/sheep/config';


const update = defineStore({
  id: 'update',
  state: () => ({
		update: false,
		data: {},
		link: {},
		download: {
			path: null,
			start: false,
			install: false,
			progress: 0,
			totalBytesWritten: 0,
			totalBytesExpectedToWrite: 0,
		},
		task: null
  }),
  actions: {
	  
    async update() {
		debug ? console.log("go update, plus.runtime.version=", plus.runtime.version) : '';
		//uni.removeStorageSync('sheep:update');
		
		// #ifdef APP-PLUS
		let storage = uni.getStorageSync('sheep:update');
		if (!storage.ignore) {
			const res = await appApi.update();
			debug ? console.log("appApi.update", res) : '';
			
			if (res.data !== null) {
				// 获取本地缓存
				debug ? console.log("local appVersion="+appVersion, Number(appVersion)) : '';
				debug ? console.log("api appVersion="+res.data.app_version, Number(res.data.app_version)) : '';
				debug ? console.log(appVersion !== res.data.app_version) : '';
				
				if (appVersion !== res.data.app_version) {
					let app_url = res.data.app_url;
					
					if(app_url){
						this.link.url = app_url;
						
						//如果是apk则强制更新，否则则update
						if(app_url.match(RegExp(/.apk/))){
							this.link.type = 'apk';
						}
						
						if(app_url.match(RegExp(/.wgt/))){
							this.data['update'] = true;
							this.link.type = 'wgt';
						}
						
						this.download();
					}
				}else{
					// 如果有缓存删除
					if (storage.path) {
						uni.removeSavedFile({
							filePath: storage.path,
							success: (res) => {
								uni.removeStorageSync('sheep:update');
							}
						});
					}
				}
			}else{
				debug ? console.log('暂未发现任何更新版本') : '';
			}
		}
		// #endif
    },
	async download() {
		debug ? console.log("go download") : '';
		let that = this;
		
		// #ifdef APP-PLUS
		let storage = uni.getStorageSync('sheep:update');
		debug ? console.log("storage", storage) : '';

		// 判断是否下载过，下载过安装
		if (storage.path) {
			debug ? console.log('已经下载过，未安装') : '';
			debug ? console.log("link",this.link.type == 'wgt', this.link.type == 'apk',  this.link) : '';
			
			this.data['update'] = false;
			
			if (this.link.type == 'wgt') {
				this.download.path = storage.path;
				this.install();
			}else if(this.link.type == 'apk'){
				plus.runtime.openURL(this.link.url);
			}
		}else{
			// 判断下载类型
			if (this.link.type == 'wgt') {
				this.download.start = true;
				// 创建下载任务对象
				this.task = uni.downloadFile({
					url: this.link.url,
					success: (res) => {
						if (res.statusCode === 200) {
							// 保存下载的安装包
							uni.saveFile({
								tempFilePath: res.tempFilePath,
								success: (file) => {
									// 本地缓存
									uni.setStorage({
										key: 'sheep:update',
										data: {
											path: file.savedFilePath,
											ignore: false
										}
									});
									// 保存地址
									that.download.path = file.savedFilePath;
									// 任务完成，关闭下载任务
									that.task.abort();
									that.task = null;
									that.download.start = false;
									that.install();
								}
							});
						}else{
							uni.showToast({
							    title: `有更新，但更新文件异常：${this.link.url}`,
								icon: 'none',
							    duration: 5000
							});
						}
					}
				});
				// 进度条更新
				that.task.onProgressUpdate((res) => {
					// 下载进度百分比
					that.download.progress = res.progress;
					// 已经下载的数据长度，单位 Bytes
					that.download.totalBytesWritten = res.totalBytesWritten;
					// 预期需要下载的数据总长度，单位 Bytes
					that.download.totalBytesExpectedToWrite = res.totalBytesExpectedToWrite;
				});
			}else if(this.link.type == 'apk'){
				// 弹出更新
				debug ? console.log('弹出更新') : '';
				plus.runtime.openURL(this.link.url);
			}
		}
		// #endif
	},
	
	async install() {
		let that = this;
		
		debug ? console.log('开始安装', that.download.path) : '';
		
		// #ifdef APP-PLUS
		// 更新状态
		this.download.install = true;
		// 安装更新
		plus.runtime.install(that.download.path, {force: true}, function() {
			debug ? console.log('plus.runtime.install', that.download.path) : '';
			
			// 更新状态
			that.data['update']=  false;
			that.download.install = false;
			plus.runtime.restart();
			
		}, function(e) {
			// 更新状态
			that.download.install = false;
		    uni.showToast({
		        title: `安装失败：${e.message}`,
				icon: 'none',
		        duration: 8000
		    });
		});
		// #endif
	},
	
	
	
  },
  
  
});

export default update;
